package com.xuanzheng.company.dao.impl;

import com.xuanzheng.company.dao.AttendanceRecordDao;
import com.xuanzheng.company.entity.AttendanceRecord;
import com.xuanzheng.company.util.DBUtil;
import com.xuanzheng.company.util.IdGenerator;

import java.sql.*;

public class AttendanceRecordDaoImpl implements AttendanceRecordDao {

    @Override
    public int save(AttendanceRecord record) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO attendance_record (id, company_id, user_id, employee_number, check_in_time, " +
                    "check_out_time, attendance_date) VALUES (?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            
            // 生成唯一ID
            String id = IdGenerator.generateId();
            record.setId(id);
            
            pstmt.setString(1, record.getId());
            pstmt.setString(2, record.getCompanyId());
            pstmt.setString(3, record.getUserId());
            pstmt.setString(4, record.getEmployeeNumber());
            pstmt.setTimestamp(5, record.getCheckInTime());
            pstmt.setTimestamp(6, record.getCheckOutTime());
            pstmt.setDate(7, record.getAttendanceDate());
            
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public int update(AttendanceRecord record) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE attendance_record SET check_in_time = ?, check_out_time = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            
            pstmt.setTimestamp(1, record.getCheckInTime());
            pstmt.setTimestamp(2, record.getCheckOutTime());
            pstmt.setString(3, record.getId());
            
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public AttendanceRecord getById(String id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        AttendanceRecord record = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT ar.*, u.name as user_name, c.name as company_name, " +
                    "ce.department, ce.position " +
                    "FROM attendance_record ar " +
                    "LEFT JOIN user u ON ar.user_id = u.id " +
                    "LEFT JOIN company c ON ar.company_id = c.id " +
                    "LEFT JOIN company_employee ce ON ar.user_id = ce.user_id AND ar.company_id = ce.company_id " +
                    "WHERE ar.id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                record = mapResultSetToAttendanceRecord(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return record;
    }

    @Override
    public AttendanceRecord getByUserIdAndDate(String userId, Date date) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        AttendanceRecord record = null;

        try {
            conn = DBUtil.getConnection();
            
            // 使用更简单的SQL查询，直接查询attendance_record表
            String sql = "SELECT * FROM attendance_record WHERE user_id = ? AND attendance_date = ?";
            
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            pstmt.setDate(2, date);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                // 直接从结果集构建记录
                record = new AttendanceRecord();
                record.setId(rs.getString("id"));
                record.setUserId(rs.getString("user_id"));
                record.setCompanyId(rs.getString("company_id"));
                record.setEmployeeNumber(rs.getString("employee_number"));
                record.setCheckInTime(rs.getTimestamp("check_in_time"));
                record.setCheckOutTime(rs.getTimestamp("check_out_time"));
                record.setAttendanceDate(rs.getDate("attendance_date"));
                record.setCreateTime(rs.getTimestamp("create_time"));
                record.setUpdateTime(rs.getTimestamp("update_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return record;
    }

    // 辅助方法：将ResultSet映射到AttendanceRecord对象
    private AttendanceRecord mapResultSetToAttendanceRecord(ResultSet rs) throws SQLException {
        AttendanceRecord record = new AttendanceRecord();
        record.setId(rs.getString("id"));
        record.setCompanyId(rs.getString("company_id"));
        record.setUserId(rs.getString("user_id"));
        record.setEmployeeNumber(rs.getString("employee_number"));
        record.setCheckInTime(rs.getTimestamp("check_in_time"));
        record.setCheckOutTime(rs.getTimestamp("check_out_time"));
        record.setAttendanceDate(rs.getDate("attendance_date"));
        record.setCreateTime(rs.getTimestamp("create_time"));
        record.setUpdateTime(rs.getTimestamp("update_time"));
        
        // 额外字段
        if (rs.getString("user_name") != null) {
            record.setUserName(rs.getString("user_name"));
            record.setEmployeeName(rs.getString("user_name")); // 设置员工姓名
        }
        if (rs.getString("company_name") != null) {
            record.setCompanyName(rs.getString("company_name"));
        }
        if (rs.getString("department") != null) {
            record.setDepartment(rs.getString("department"));
        }
        if (rs.getString("position") != null) {
            record.setPosition(rs.getString("position"));
        }
        
        // 设置打卡日期字符串
        if (record.getAttendanceDate() != null) {
            record.setRecordDate(record.getAttendanceDate().toString());
        }
        
        // 设置迟到和早退状态
        // 这里我们简单地将这些字段设为false，实际上应该根据公司考勤规则判断
        // 但为了确保字段不为null，我们设置默认值
        record.setLate(false);
        record.setEarlyLeave(false);
        
        return record;
    }
} 